/**
 * @modal: 智能策略手动&自动执行记录
 */
import CommonModal from '@/components/CommonModal';
import ProTable from "@/components/ProTable";
import { Button, DatePicker, Space, Select, Radio, Form, Input, Alert } from "antd";
import { useState, useEffect } from "react";
import CommonPage from '@/components/CommonPagination';
import Api from "../service";
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;

function ExecuteRecord({ type = 0, handleCancel }) {
	const [open, setOpen] = useState(false);

	const [form] = Form.useForm();

	const [searchKey, setSearchKey] = useState();
	//策略列表
	const [executeRecord, setExecuteRecord] = useState([]);
	//分页数据
	const [pages, setPages] = useState({
		current: 1,
		total: 0,
		pageSize: 100,
		pageSizeOptions: ['10', '20', '100', '500']
	})
	const columns = [
		{
			title: "序号",
			code: "name",
			width: 60,
			render: (t, r, i) => {
				return i + 1;
			}
		},
		{
			title: "创建时间",
			code: "createTime",
			render: t => {
				return t && moment(t).format('YYYY-MM-DD HH:mm:ss');
			}
		},
		{
			title: "开始执行时间",
			code: "startExecuteTime",
			render: t => {
				return t && moment(t).format('YYYY-MM-DD HH:mm:ss');
			}
		},
		{
			title: "结束执行时间",
			code: "endExecuteTime",
			render: t => {
				return t && moment(t).format('YYYY-MM-DD HH:mm:ss');
			}
		},
		{
			title: "运行结果",
			code: "executeSimpleResult",
			render: t => {
				return t;
			}
		},
	];

	//自动执行记录需要添加此列
	if(type == 1) {
		columns.splice(3, 0, {
			title: "下次执行时间",
			code: "nextExecuteTime",
			render: t => {
				return t && moment(t).format('YYYY-MM-DD HH:mm:ss');
			}
		})
	}

	useEffect(() => {
		setOpen(true);
	}, []);

	useEffect(() => {
		getExecuteRecord();
	}, [searchKey])

	//获取执行记录
	const getExecuteRecord = async () => {
		START_LOADING();
		const formVal = form.getFieldsValue();
		const params = {
			type,
			pageNum: pages.current,
			pageSize: pages.pageSize,
		}
		if (formVal.createTime) {
			params.startCreateTime = moment(formVal.createTime[0]).format('YYYY-MM-DD 00:00:00');
			params.endCreateTime = moment(formVal.createTime[1]).format('YYYY-MM-DD 23:59:59');
		}
		const { success, data } = await Api.getExecuteRecord(params);
		if (success) {
			setExecuteRecord(data.records);
			setPages({
				...pages,
				total: data.total
			})
		}
		END_LOADING();
	};

	//点击查询
	const onFinish = () => {
		setPages({
			...pages,
			current: 1
		})
		setSearchKey(Date.now() + '');
	}

    //点击重制
    const onReset = () => {
        form.resetFields();
		setPages({
			...pages,
			current: 1
		})
		setSearchKey(Date.now() + '');
    }

	//变更时间
	const changeTimeRange = e => {
		const val = e.target.value;
		const arr = val == 1 ? [moment().startOf('day').subtract(val, 'days'), moment().endOf('day').subtract(val, 'days')] : [moment().startOf('day').subtract(val, 'days'), moment().endOf('day')];
		form.setFieldsValue({ createTime: arr });
		setPages({
			...pages,
			current: 1
		})
		setSearchKey(Date.now() + '');
	}

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		handleCancel();
	};

	const ProTableProps = {
		data: executeRecord,
		columns,
		style: {
			maxHeight: '40vh',
		}
	}
	//分页数据
	const PageProps = {
		pagination: pages,
		handleChange(current, size) {
			const obj = { ...pages, current, pageSize: size };
			setPages(obj);
			setSearchKey(Date.now() + '');
		}
	}

	const title = type== 1 ? '执行记录（自动）' : '执行记录（手动）';
	
	return (
		<CommonModal
			title={title}
			footer={null}
			className="views-table-dialog"
			afterClose={afterClose}
			open={open}
			width="960px"
			onCancel={onCancel}
		>
			<div className='views-container' style={{ paddingBottom: '12px' }}>
				<Alert description="注：只保留最新一个月的执行记录" />
				<Form
					name="execute-record-form"
					form={form}
					layout='inline'
					size='small'
					onFinish={onFinish}
					initialValues={{
						timeType: 'create',
						createTime: [moment().startOf('day').subtract(7, 'days'), moment().endOf('day')]
					}}
					style={{ margin: '12px 0' }}
				>
					<Form.Item>
						<Input.Group compact>
							<Form.Item
								name="timeType"
								noStyle
							>
								<Select placeholder="请选择">
									<Option value="create">创建时间</Option>
								</Select>
							</Form.Item>
							<Form.Item
								name="createTime"
								noStyle
							>
								<RangePicker format="YYYY-MM-DD" />
							</Form.Item>
						</Input.Group>
					</Form.Item>
					<Form.Item name="timeRange">
						<Radio.Group buttonStyle="solid" onChange={changeTimeRange}>
							<Radio.Button value="7">近七天</Radio.Button>
							<Radio.Button value="3">近三天</Radio.Button>
							<Radio.Button value="1">昨天</Radio.Button>
							<Radio.Button value="0">今天</Radio.Button>
						</Radio.Group>
					</Form.Item>
					<Form.Item label=" " colon={false}>
						<Space>
							<Button type="primary" htmlType="submit">查询</Button>
							<Button onClick={onReset} htmlType="reset">重置</Button>
						</Space>
					</Form.Item>
				</Form>
				<ProTable {...ProTableProps} />
				<div style={{ marginTop: '12px' }}>
					<CommonPage {...PageProps} />
				</div>
			</div>
		</CommonModal>
	);
}

export default ExecuteRecord;
